<?php
/**
 * Feeds manager Component
 *
 * @package		yos_news_crawler
 * @subpackage	CMS
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
JTable::addIncludePath(JPATH_COMPONENT_SITE.DS.'cms'.DS.'joomlapost'.DS.'tables');
require_once(JPATH_COMPONENT_SITE.DS.'helpers'.DS.'phpWebHacks.php');
class YOS_Cms_Joomlapost extends JObject {
	//object article
	private $_arr_article;
	
	public $_db		=	null;
	
	//store job id key
	private $_job_configuration;
	
	var $cms_config	=	array();
	
	public function __construct($job_configuration, $arr_article)
	{
		$this->_job_configuration = $job_configuration;
		$this->_arr_article = $arr_article;
		if (!$this->_db	=	$this->getDBO()) {
			return false;
		}
		$this->_get_cmsconfig();	
	}
			
	//when job call store_article function,
	//-store images file
	//-build Joomla article
	//-store in database
	
	function getDBO()
	{
		require(JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'joomlapost'.DS.'cms_config.php');		
		$option_ 	= array(); //prevent problems 
		$option_['driver']   = $d_w_driver;       	// Database driver name
		$option_['host']     = $d_w_host;    		// Database host name
		$option_['user']     = $d_w_user;  	    	// User for database authentication
		$option_['password'] = $d_w_password;  		// Password for database authentication
		$option_['database'] = $d_w_database;  	  	// Database name
		$option_['prefix']   = $d_w_prefix;          // Database prefix (may be empty)
		if (empty($option_['user']) || empty($option_['password']) || empty($option_['database']) || empty($option_['driver']) || empty($option_['host']))
		{
			$config	=	JFactory::getConfig();
			
			$option_['driver']   = $config->getValue('dbtype');       	// Database driver name
			$option_['host']     = $config->getValue('host');    		// Database host name
			$option_['user']     = $config->getValue('user');  	    	// User for database authentication
			$option_['password'] = $config->getValue('password');  		// Password for database authentication
			$option_['database'] = $config->getValue('db');  	  	// Database name
		}
		$db_	= &JDatabase::getInstance( $option_ );
		if (!empty($db_->message)) {
				$this->msg = JText::sprintf($db_->message);
				return false;
			}	
		$this->_dbo=$db_;
		return $this->_dbo;
	}
	public function store_articles()
	{
		$db	 =& JFactory::getDBO();		
		
		$cms_params_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'joomlapost'.DS.'cms_config_job.xml';
		if(!is_readable($cms_params_file)){
			$this->setError('[CMS JOOMLA] unable to load params configure file: '.$cms_params_file);
			return false;
		}
		$params = new JParameter($this->_job_configuration->params, $cms_params_file);
		$time_plus = 0;
		
		// make browser object
/*		BEGIN MAKE	*/
			$browser = new phpWebHacks();
			$page =	$browser->get($params->get('page_login'));
//echo htmlspecialchars($page);
//die();
			$action = '';
			$form_data = $browser->parseForm('com-form-login', $action);
			if (!$action)
			{
				$action = $params->get('page_login');
			}
			if (!is_array($form_data) || !key_exists('username', $form_data) || !key_exists('passwd', $form_data)) {
				$this->setError('[CMS JOOMLA] invalid form login: '. $params->get('page_login'));
				return false;
			}		
			
			$form_data['username']  =	$params->get('username');	
			$form_data['passwd']  =  	$params->get('password');	
		//	$form_data['pass']  =  	'abx';	
			
			$response = $browser->post($action, $form_data);			
			
			if (preg_match('/<dd\s*class="error message fade">\s*<ul>\s*<li>[^<>]*<\/li>\s*<\/ul>\s*<\/dd>/ism',$response,$match)) {	
			
				$page_mess	=	preg_replace('/<a[^>]*>.*?<\/a>/','',$match[1]);
				$page_mess	=	preg_replace('/<p[^>]*>.*?<\/p>/','',$page_mess);
				$this->setError('[CMS JOOMLA] error login: '. $params->get('page_login')."\r\n\t\t message: $page_mess");
				return false;
			}
/*			END MAKE	*/			
		foreach ($this->_arr_article as &$article){
			//check article link is exist			
			$query = "SELECT COUNT(*) FROM #__yos_content_link WHERE `link` = ".$db->Quote($article->link)." 
				AND `cms` = 'joomlapost'";
			$db->setQuery($query);
			$is_exist = $db->loadResult();
			if ($db->getErrorNum()) {
				$arr_error = debug_backtrace();
				$this->setError('[CMS JOOMLAPOST] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
				return false;
			}
			if ($is_exist) {
				echo $article->link.' is exit'.'<br />';
				continue;
			}			
			$row = $this->_store_article($article, $params, $time_plus,$browser);			
			if (!$row) {
				return false;
			}
			$time_plus = $time_plus + 10;
			if (!$row) {
				continue;
			}		
			
			$this->_added_fetched_article($article->link, $row);		
		}
	}	
	//get cms configuration
	private function _get_cmsconfig()
	{
		if ($this->cms_config) {
			return $this->cms_config;
		}
		$config_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'joomlapost'.DS.'cms_config.php';
		if(!is_readable($config_file)){
			$this->setError('[CMS JOOMLA] unable to load configure file: '.$config_file);
			return false;
		}
		require($config_file);	
		$this->cms_config['image_path_root']	=	$image_path_root;
		$this->cms_config['image_url_root']		=	$image_url_root;
		return $this->cms_config;
	}			
	
	//store an article to database
	private function _store_article(&$obj_article, $params, $time_plus,$browser)
	{
		$db	 =& $this->_db;	
		if (!$obj_article->full_text) {
			$obj_article->full_text	=$obj_article->intro_text;
		}
		// process title
		$db_drupal	=	$this->getDBO();
		$obj_article->title	=	str_replace('/\\r|\\n/','',htmlspecialchars($obj_article->title));
		$obj_article->title	=	str_replace("/\\r|\\n/",'',htmlspecialchars($obj_article->title));
		$obj_article->title	=	str_replace('\n','',$obj_article->title);
		$obj_article->title	=	str_replace('\r','',$obj_article->title);
		$obj_article->title	=	str_replace("\n",'',$obj_article->title);
		$obj_article->title	=	str_replace("\r",'',$obj_article->title);
	
		//add according info
		$str_source_content = $this->_job_configuration->according_to;
		//readmore (add original source link)		
		$obj_article->full_text =$obj_article->full_text."\n".'<p class="according">'.$str_source_content.'</p>';	
		
		//title ads
		if ($this->_job_configuration->title_ext) {
			if ($this->_job_configuration->title_ext_pos == 0) {
				$obj_article->title = $this->_job_configuration->title_ext . $obj_article->title;
			}
			else {
				$obj_article->title = $obj_article->title . $this->_job_configuration->title_ext;
			}			
		}		
		//intro ads
		if ($this->_job_configuration->ads) {
			if ($this->_job_configuration->catads == 0) {
				$obj_article->intro_text = $this->_job_configuration->ads . $obj_article->intro_text;
			}
			else {
				$obj_article->intro_text = $obj_article->intro_text . $this->_job_configuration->ads;
			}			
		}
		// 
			$page =	$browser->get($params->get('page_post'));
		
			$action = '';
			$form_data = $browser->parseForm('adminForm', $action);
			
			if (!is_array($form_data) || !key_exists('created_by',$form_data)) {
				$this->setError('[CMS JOOMLAPOST] invalid form post content: '.$params->get('page_post'));
				$sdb	=	JRequest::getInt('showdebug',0);
				if ($sdb) {					
					echo '<br /><hr />';
					var_dump($form_data);
					echo $page;				
				}
				return false;				
			}
			if (!$action)
			{
				$action = $params->get('page_post');
			}
			$time_now		= JFactory::getDate();
			$time_now		= $time_now->toUnix() + $time_plus;//seconds
			$time_now		=	date('Y-m-d',$time_now);
			
			$form_data['title']					=	$obj_article->title;
			
			$form_data['text']					=	$obj_article->intro_text.' <hr id="system-readmore" /> '.$obj_article->full_text;			
			$form_data['sectionid']				=	intval($params->get('sectionid'));
			$form_data['catid']					=	intval($params->get('catid'));
			
			$form_data['frontpage']				=	$params->get('front_page');
			$form_data['publish_up']			=	$params->get('publish_time');
			$form_data['publish_down']			=	$params->get('publish_down');
			$form_data['access']				=	$params->get('access');										
			$form_data['task']					=	'save';							
			
			$response = $browser->post($action, $form_data);			
		
		return $obj_article;
	}			

	// update to yos_content_link
	private function _added_fetched_article($link, $row){
		$db		=&	JFactory::getDBO();
		$query	=	"INSERT INTO #__yos_content_link SET
			`link`	=	".$db->Quote($link).", 
			`title`	=	".$db->Quote($row->title).", 
			`cms`	=	".$db->Quote('joomlapost').", 
			`articleid`	= ". $db->Quote('joomlapost_id');
		$db->setQuery($query);
		$db->query();
		
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[CMS JOOMLA] Fail to insert fetched article to list: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
			return false;
		}
		$time_now		= JHTML::_('date','','%Y-%m-%d %H:%M:%S');
		$fp = fopen( JPATH_COMPONENT_SITE.DS.'cms'.DS.'joomlapost'.DS.'log_article.txt', 'a');
			fputs($fp, "__________________________________________________\r\n");
			fputs($fp, "__________________________________________________\r\n");
			fputs($fp, "--------------------------------------------------\r\n");
			fputs($fp, "------Run time: $time_now ------\r\n");
			fputs($fp, "------Title: $row->title ------\r\n");			
			fputs($fp, "------Link: $link ------\r\n");			
			fclose($fp);
		return true;
	}

}